package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import com.tanhua.model.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     *
     * @param map
     * @return
     */
    public Map login(Map map) {
        //获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //校验验证码
        String redisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(redisCode) || !verificationCode.equals(redisCode)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(Constants.CAP_CODE + uuid);
        //根据用户名查询数据
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Admin admin = adminMapper.selectOne(wrapper);

        //判断是否存在，密码是否一致，将传递过来的密码加密再进行比较
        password = SecureUtil.md5(password);
        if (admin == null || !password.equals(admin.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        //生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        tokenMap.put("username",admin.getUsername());
        String token = JwtUtils.getToken(tokenMap);
        //返回token给前端页面
        Map returnMap = new HashMap();
        returnMap.put("token",token);
        return returnMap;
    }

    /**
     * 获取当前用户信息
     * @return
     */
    public AdminVo profile() {
        Long id = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(id);
        return AdminVo.init(admin);
    }
}